package com.mdhw.mili.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdhw.ali.service.AliService;
import com.mdhw.common.base.PageData;
import com.mdhw.common.enums.StatusEnum;
import com.mdhw.config.R;
import com.mdhw.device.dao.MiliOpenDoorLogDao;
import com.mdhw.device.entity.MiliOpenDoorLog;
import com.mdhw.device.service.MiliOpenDoorLogService;
import com.mdhw.device.vo.MiliOpenDoorLogVo;
import com.mdhw.mili.service.MiliDeviceService;
import com.mdhw.mili.service.MiliTokenService;
import com.mdhw.mili.vo.device.OpenDoorReqVo;
import com.mdhw.mili.vo.device.ProjectDeviceInfoOpenReqVo;
import com.mdhw.mili.vo.result.MiliResultVo;
import com.mdhw.system.vo.SysUserExchangeJifenLogVo;
import com.mdhw.utils.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class MiliDeviceServiceImpl implements MiliDeviceService {

    @Autowired
    private AliService aliService;
    @Autowired
    private MiliOpenDoorLogDao miliOpenDoorLogDao;

    @Autowired
    private MiliOpenDoorLogService miliOpenDoorLogService;

    @Value("${mili.device.openDoor}")
    private String oepnDoorUrl;
    @Autowired
    private MiliTokenService miliTokenService;
    /**
     * 米立-设备-设备操作-远程开门
     * @param openDoorReqVo
     * @return
     */
    @Override
    public R openDoor(OpenDoorReqVo openDoorReqVo) {

        long startTime = System.currentTimeMillis();
        Map<String,String> returnMap = new HashMap<>();
        String token = this.miliTokenService.buildMiliToken();
        ProjectDeviceInfoOpenReqVo projectDeviceInfoOpenVo = openDoorReqVo.getProjectDeviceInfoOpenVo();
        String jsonString = JSONObject.toJSONString(projectDeviceInfoOpenVo);

        String response1 = projectDeviceInfoOpenVo.getResponse();
        String sign = projectDeviceInfoOpenVo.getSign();
        String mobile = projectDeviceInfoOpenVo.getMobile();
        try {
            mobile = this.aliService.jiemiPhone(response1, sign);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        returnMap.put("mobile",mobile);


        Map<String,Object> params1 = new HashMap<>();
        params1.put("deviceId","9a603164c4b74815a3a6f82adc2d60b8");
        params1.put("personType","2");
        params1.put("mobile","18950462412");
        Map params = JSONObject.parseObject(jsonString, Map.class);
        log.info("params:{}", params);
        log.info("params1:{}", params1);
        Map<String,String> headers = new HashMap<>();
        headers.put("Authorization", token);
        headers.put("PROJECT_ID", "48bea48c8d6a46cd84759bce498e610b");
        OkHttpUtil okHttpUtil = OkHttpUtil.getInstance();

        Date nowTime = new Date();
        MiliOpenDoorLog miliOpenDoorLog = new MiliOpenDoorLog();
        miliOpenDoorLog.setCreateDate(nowTime );
        miliOpenDoorLog.setUpdateDate(nowTime );
        miliOpenDoorLog.setPhone(mobile);
        miliOpenDoorLog.setStatus(StatusEnum.OK.getCode());
        miliOpenDoorLog.setRevision(0);
        miliOpenDoorLog.setDeviceId("9a603164c4b74815a3a6f82adc2d60b8");
        miliOpenDoorLog.setSortNum(0);


        try {
            Long outStartTime = System.currentTimeMillis();
            Response response = okHttpUtil.postDataWithBodyWithHeader(this.oepnDoorUrl, params1, headers);
            Long outEndTime = System.currentTimeMillis();
            Integer outRequestTime = (int)(outEndTime - outStartTime);
//            log.info("response2: {}", response.body().toString());
//            log.info("response3: {}", response.toString());

            String resultStr = response.body().string();
            log.info("response1: {}", resultStr);

            if(StringUtils.isNotBlank(resultStr)){
                JSONObject jsonObject = JSONObject.parseObject(resultStr);
                Integer code = jsonObject.getInteger("code");
                if(code == 0){
                    returnMap.put("msg","开门成功");
                    miliOpenDoorLog.setOpenStatus(1);
                    long endTime = System.currentTimeMillis();
                    Integer requestTime = (int)(endTime - startTime);
                    miliOpenDoorLog.setRequestTime(requestTime);
                    miliOpenDoorLog.setOutRequestTime(outRequestTime);
                    this.miliOpenDoorLogService.save(miliOpenDoorLog);

                    return R.success(returnMap);
                }
            }
            returnMap.put("msg","开门失败");
            miliOpenDoorLog.setOpenStatus(0);
            this.miliOpenDoorLogService.save(miliOpenDoorLog);
            return R.error(-1,"开门失败",returnMap);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public R<PageData<MiliOpenDoorLogVo>> selectMiliOpenDoorLogPage(Integer pageNo, Integer pageSize, String mobile) {
        Page page = new Page(pageNo, pageSize);
        QueryWrapper<MiliOpenDoorLogVo> modlvQw = new QueryWrapper<>();
        modlvQw.eq("phone", mobile);
        modlvQw.orderByDesc("id");
        this.miliOpenDoorLogDao.selectMiliOpenDoorLogPage(page,modlvQw);
        PageData pageData = PageData.plusPageToPageData(page);
        return R.success(pageData);
    }
}
